package cn.com.dhcc.ddi.task.service;


import cn.com.dhcc.app.core.service.Log;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 导出Excel表格
 *
 * @日期 2016-4-27 下午2:36:57
 * @作者 macky_he
 * @版本 [地下水V1.0]
 */
@Service
public class ExportExcelService {

    @SuppressWarnings("deprecation")
    private static Logger logger = Log.getExistLogger(Log.LOGTYPE.ADAPTER);

    public static SimpleDateFormat format = new SimpleDateFormat(
            "yyyyMMddHHmmss");

    /**
     * 导出Excel
     *
     * @param vo
     * @param response
     *            输出
     */
    public void exportExcel(ChangeVo vo, HttpServletRequest request,
                            List<String> fileNames) {
        logger.info("进入exportExcel()...");
        Map<String, List<ChangeVo.RowPro>> dataMap = vo.getTableData();
        excelUtil(dataMap, "insert", request, fileNames);
        vo = null;
        dataMap = null;
        logger.info("exportExcel()结束...");
    }

    @SuppressWarnings({ "deprecation", "resource" })
    private void excelUtil(Map<String, List<ChangeVo.RowPro>> dataMap,
                           String name, HttpServletRequest request, List<String> fileNames) {
        if (null == dataMap || dataMap.size() <= 0) {
            return;
        }
        for (String tableName : dataMap.keySet()) {
            String file = request.getRealPath("/temp_files") + File.separator
                    + tableName + "_" + format.format(new Date())+"_"+System.currentTimeMillis() + ".xls";
            fileNames.add(file);
            logger.info("开始生成" + file);
            String sheetName = tableName + "-" + name;
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet(sheetName);
            // 内容的样式
            HSSFCellStyle content_style = workbook.createCellStyle();
            HSSFCellStyle title_style = workbook.createCellStyle();
            HSSFFont title_font = workbook.createFont();
            title_font.setColor(HSSFColor.VIOLET.index);
            title_font.setFontHeightInPoints((short) 12);
            title_font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            title_style.setFont(title_font);
            HSSFFont content_font = workbook.createFont();
            content_font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
            content_style.setFont(content_font);
            // 填充标题内容
            HSSFRow excelRow = sheet.createRow(0);
            try {
                List<ChangeVo.RowPro> list = dataMap.get(tableName);
                String[] cols = null;// 字段集合
                ChangeVo.RowPro row = list.get(0);
                Map<String, ChangeVo.ColPro> colsMap = row.getColMap();// 字段集合
                cols = new String[colsMap.size()];// 字段
                colsMap.keySet().toArray(cols);
                for (int j = 0; j < cols.length; j++) {
                    HSSFCell cell = excelRow.createCell(j);
                    cell.setCellStyle(title_style);
                    HSSFRichTextString text = new HSSFRichTextString(cols[j]);
                    cell.setCellValue(text);
                }
                logger.info(tableName + "数据数量为：" + list.size());
                for (int i = 0; i < list.size(); i++) {
                    excelRow = sheet.createRow(i + 1);
                    for (int k = 0; k < cols.length; k++) {
                        HSSFCell cell = excelRow.createCell(k);
                        cell.setCellStyle(content_style);
                        HSSFRichTextString text = new HSSFRichTextString(list
                                .get(i).getColMap().get(cols[k]).getValue());
                        cell.setCellValue(text);
                    }
                }
            } catch (Exception e) {
                fileNames.remove(file);
                logger.error(file + "填充excel时发生异常", e);
                continue;
            }
            FileOutputStream o = null;
            try {
                o = new FileOutputStream(file);
                workbook.write(o);
                logger.info(file + "文件导出成功...");
            } catch (Exception e) {
                fileNames.remove(file);
                logger.error(file + "导出文件发生异常：", e);
                continue;
            } finally {
                try {
                    o.close();
                } catch (IOException e) {
                    logger.error("关闭FileOutputStream发生异常：", e);
                }
            }
        }
    }

}

